package com.bigflexlib.utils
{


	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	


	/**
	 * 
	 * Utility class that provides non invasive change consolidation over
	 * objects that expose enable/disableAutoUpdate or autoUpdateFlags
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */	
	public class AutoUpdateTicker implements IDisposable
	{
		
		
		private var target:Object;
		
		
		private var timer:Timer;
		
		
		/**
		 * 
		 * @param target
		 * @param delay
		 * 			in milliseconds
		 * 
		 */		
		public function AutoUpdateTicker( target:Object, delay:int )
		{
			
			this.target = target;
			
			autoUpdate( false );
			
			timer = new Timer( delay, 0 );
			
			timer.addEventListener( TimerEvent.TIMER, onTimer );
			
			timer.start( );
		}



		private function onTimer( event:TimerEvent ):void
		{
		
			autoUpdate( true );
		
			autoUpdate( false );
		
		}


		private function autoUpdate( enable:Boolean ):void
		{

			if ( target is AutoUpdateFlag )
			{
				var auf:AutoUpdateFlag = target as AutoUpdateFlag;
				if ( enable )
					auf.enable( );
				else
					auf.disable( );
			}
			else if ( target is ArrayCollection )
			{
				var ac:ArrayCollection = target as ArrayCollection;
				
				if ( enable )
					ac.enableAutoUpdate( );
				else
					ac.disableAutoUpdate( );
			
			}
		
		}




		public function dispose( ):void
		{
			timer.stop( );

			timer.removeEventListener( TimerEvent.TIMER, onTimer );
			
			timer = null;
			
			target = null;	
	
		}
		
		
		
		
		private static var cache:Dictionary = new Dictionary( true );
		/**
		 * 
		 * Convenience function to create an autoupdate ticker.
		 * If an autoupdate ticker was already created, it is removed
		 * 
		 * @param target
		 * @param delay
		 * 
		 */		
		public static function activate( target:Object, delay:int ):void
		{
			deactivate( target );
			
			cache[ target ] = new AutoUpdateTicker( target, delay );
		}
		

		public static function deactivate( target:Object ):void
		{
			try{
				cache[ target ].dispose();
				delete cache[target];
			}catch ( e:Error ){}
		}		
		
		
	}
	
}